package com.itbbfx.service.system.impl;

import com.itbbfx.entity.*;
import com.itbbfx.mapper.MenuMapper;
import com.itbbfx.mapper.RoleMapper;
import com.itbbfx.mapper.UserMapper;
import com.itbbfx.service.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Role> initUserRole() {
        return roleMapper.initUserRole();
    }

    @Override
    public List<Role> selectAllRole(Role role) {
        return roleMapper.selectAllRole(role);
    }

    @Override
    public int queryRoleName(String rolename) {
        return roleMapper.queryRoleName(rolename);
    }

    @Override
    public String addRole(Role role) {
        if(roleMapper.addRole(role) > 0) {
            return "角色添加成功！";
        }

        return "角色添加失败！";
    }

    @Override
    public String updateRole(Role role) {
        if(roleMapper.updateRole(role) > 0) return "角色修改成功！";
        return "角色修改失败！";
    }

    @Override
    public String deleteRole(int roleid) {
        if(userMapper.countUserRole(roleid) > 0){
            return "请删除分配给用户的角色后再删除角色！";
        }
        if(roleMapper.queryUserRole(roleid) > 0){
            roleMapper.deleteUserRole(roleid);
        }

        if(roleMapper.queryRoleMenu(roleid) > 0){
            roleMapper.deleteRoleMenu(roleid);
        }

        if(roleMapper.deleteRole(roleid)>0){
            return "删除成功！";
        }


        return "删除失败！";
    }

    @Override
    public int saveRoleMenu(RoleMenu roleMenu) {
        if(roleMapper.queryRoleMenu(roleMenu.getRoleid()) > 0){
            roleMapper.deleteRoleMenu(roleMenu.getRoleid());
        }

        return roleMapper.saveRoleMenu(roleMenu);
    }

    @Override
    public DataGridView initRoleMenu(int roleid) {
        List<Menu> menus = menuMapper.initRoleMenu();
        List<Integer> menuIds = roleMapper.initRoleMenu(roleid);

        List<TreeNode> ms = new ArrayList<>();
        for (Menu menu : menus) {
            String checkArr= "0";

            for (Integer menuid : menuIds){
                if(menuid == menu.getId()){
                    checkArr = "1";
                    break;
                }
            }

            ms.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),menu.getSpread()==true,checkArr));
        }

        return new DataGridView(ms);
    }
}